package com.westar.tv;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.westar.tv.utils.FileUtils;
import com.westar.tv.utils.NetUtils;
import com.westar.tv.utils.SharePreferencesUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;

/**
 * Created by ZWP on 2019/10/11 14:56.
 * 描述：
 */
public class MainActivity extends BaseActivity {
    WebView webView;
    RelativeLayout mask;
    String url_prefix;
    String url_suffix;

    final static int SETTING_REQUEST_CODE = 0;

    final static int CHOOSER_REQUEST_CODE = 9;

    final static int CAMERA_REQUEST_CODE = 10;

    final static int RECEIVE_SPEECH_WHAT = 0;

    //设置的刷新间隔时间 默认一小时  毫秒
    long DELAYMILLIS = 1000 * 60 * 60;
    //触发刷新间隔时间  毫秒
    long PLAY_DELAYMILLIS = 1000 * 10;
    //上次触摸屏幕时间
    Long touchTimes = System.currentTimeMillis();
    //实例化自动刷新线程
    MRunnable mRunnable = new MRunnable();

    private NetChangeReceiver netChangeReceiver;

    private ValueCallback<Uri> mUploadMessage;

    private ValueCallback<Uri[]> mUploadCallbackAboveL;

    private String cameraPath;
    private Uri cameraUri;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == RECEIVE_SPEECH_WHAT) {
                Bundle data = msg.getData();
                String txtId = data.getString("txtId");
                String speechStr = data.getString("speechStr");
                String function = data.getString("function");
                StringBuffer sb = new StringBuffer();
                boolean ls = false;
                try {
                    JSONObject root = new JSONObject(speechStr);
                    ls = root.getBoolean("ls");
                    Log.i("ls:", String.valueOf(ls));
                    JSONArray ws = root.getJSONArray("ws");
                    for (int i = 0; i < ws.length(); i++) {
                        JSONArray cw = ws.getJSONObject(i).getJSONArray("cw");
                        for (int j = 0; j < cw.length(); j++) {
                            JSONObject w = cw.getJSONObject(j);
                            sb.append(w.getString("w"));
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                webView.loadUrl("javascript:$('#" + txtId + "').val($('#" + txtId + "').val()+'" + sb + "')");
                if (ls) {
                    webView.loadUrl("javascript:" + function + "()");
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除title
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //去掉虚拟按键全屏显示
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        setContentView(R.layout.activity_main);

        initId();

        //透明度
        mask.getBackground().setAlpha(60);

        //浏览器设置
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);//支持js
        webSettings.setUseWideViewPort(true);  //调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //  webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);  //关闭webview中缓存
        webSettings.setAllowFileAccess(true);  //设置可以访问文件
        webSettings.setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存

        webView.setWebChromeClient(new XHSWebChromeClient());

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //自动播放
                boolean media = (Boolean) SharePreferencesUtils.get(MainActivity.this, SPKeys.DEFAULT_SP_FILE_NAME, SPKeys.SETTING_MEDIA, true);
                if (media) {
                    String audioJs = "javascript: var v = document.getElementsByTagName('audio'); v[0].play();";
                    view.loadUrl(audioJs);
                    String videoJs = "javascript: var v = document.getElementsByTagName('video'); v[0].play();";
                    view.loadUrl(videoJs);
                }
                mask.setVisibility(View.GONE);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                mask.setVisibility(View.VISIBLE);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                MainActivity.this.showShortToast(errorCode + "," + description);
                view.loadUrl("file:///android_asset/error.html");
                loadUrl();
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });

        webView.addJavascriptInterface(new JavaScriptInterface(), "JavaScriptInterface");
        loadUrl();

        netChangeReceiver = new NetChangeReceiver();
        //注册广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netChangeReceiver, intentFilter);

        webView.requestFocus();

        Intent intent = getIntent();
        boolean startSetAct = intent.getBooleanExtra("startSetAct", true);
        //第一次启动才显示计数
        if (startSetAct) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(MainActivity.this, SettingActivity.class);
                    intent.putExtra("firstStart", true);
                    MainActivity.this.startActivity(intent);
                }
            }, 1000);
        }

        handler.post(mRunnable);

    }

    private void initId() {
        webView = findViewById(R.id.web_view);
        mask = findViewById(R.id.mask);
        url_prefix = getString(R.string.url_prefix);
        url_suffix = getString(R.string.url_suffix);
        webView = findViewById(R.id.web_view);

        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                goSettingAct();
                return false;
            }
        });
    }

    @Override
    protected void onResume() {
        boolean landscape = (Boolean) SharePreferencesUtils.get(this, SPKeys.DEFAULT_SP_FILE_NAME, SPKeys.SETTING_LANDSCAPE, false);
        if (landscape) {
            if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        }
        super.onResume();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
                goSettingAct();
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    private class NetChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            handler.post(new ReloadRunnable());
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_setting) {
            goSettingAct();
        }
        return super.onOptionsItemSelected(item);
    }

    private void loadUrl() {
        String url = (String) SharePreferencesUtils.get(MainActivity.this, SPKeys.DEFAULT_SP_FILE_NAME, SPKeys.SERVER_URL, Config.SERVER_URL);
        if (!TextUtils.isEmpty(url)) {
            url = url_prefix + url + url_suffix;
            webView.loadUrl(url);
            webView.requestFocusFromTouch();
        } else {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    showShortToast("请先设置访问地址");
                    goSettingAct();
                }
            }, 500);

        }
    }

    private void goSettingAct() {
        Intent intent = new Intent(this, SettingActivity.class);
        startActivityForResult(intent, SETTING_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == CHOOSER_REQUEST_CODE) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                String path = FileUtils.getPath(this, result);
                if (TextUtils.isEmpty(path)) {
                    mUploadMessage.onReceiveValue(null);
                    mUploadMessage = null;
                    return;
                }
                Uri uri = Uri.fromFile(new File(path));
                mUploadMessage.onReceiveValue(uri);
                mUploadMessage = null;
            }
        } else if (requestCode == CAMERA_REQUEST_CODE) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            String path = FileUtils.getPath(this, cameraUri);
            if (mUploadCallbackAboveL != null) {
                Uri[] results = new Uri[1];
                results[0] = Uri.fromFile(new File(path));
                mUploadCallbackAboveL.onReceiveValue(results);
                mUploadCallbackAboveL = null;

            } else if (mUploadMessage != null) {
                Uri uri = Uri.fromFile(new File(path));
                mUploadMessage.onReceiveValue(uri);
                mUploadMessage = null;
            }
        } else if (requestCode == SETTING_REQUEST_CODE) {
            loadUrl();
        }

    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != CHOOSER_REQUEST_CODE || mUploadCallbackAboveL == null) return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        String path = FileUtils.getPath(this, item.getUri());
                        results[i] = Uri.fromFile(new File(path));
                    }
                }
                if (dataString != null) {
                    Uri[] temp = new Uri[]{Uri.parse(dataString)};
                    if (temp.length > 0) {
                        results = new Uri[temp.length];
                        for (int i = 0; i < temp.length; i++) {
                            String path = FileUtils.getPath(this, temp[i]);
                            results[i] = Uri.fromFile(new File(path));
                        }
                    }
                }
            }
        }
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
        return;
    }

    class JavaScriptInterface {
        public JavaScriptInterface() {
        }

        @JavascriptInterface
        public String getAccount() {
            String account = (String) SharePreferencesUtils.get(MainActivity.this, SPKeys.DEFAULT_SP_FILE_NAME, SPKeys.ACCOUNT, "");
            return account;

        }

        @JavascriptInterface
        public String getPwd() {
            String pwd = (String) SharePreferencesUtils.get(MainActivity.this, SPKeys.DEFAULT_SP_FILE_NAME, SPKeys.PASSWORD, "");
            return pwd;
        }

        @JavascriptInterface
        public void exit() {
            app.appExit();
        }

        @JavascriptInterface
        public void getSpeech(final String txtId, final String function) {

            handler.post(new Runnable() {
                @Override
                public void run() {
                    //1.创建SpeechRecognizer对象，第二个参数：本地听写时传InitListener
                    RecognizerDialog iatDialog = new RecognizerDialog(MainActivity.this, null);
                    //2.设置听写参数，详见《科大讯飞MSC API手册(Android)》SpeechConstant类
                    iatDialog.setParameter(SpeechConstant.DOMAIN, "iat");
                    iatDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
                    iatDialog.setParameter(SpeechConstant.ACCENT, "mandarin");
                    iatDialog.setParameter(SpeechConstant.ASR_PTT, "0");
                    //3.设置回调接口
                    iatDialog.setListener(new RecognizerDialogListener() {
                        @Override
                        public void onResult(RecognizerResult recognizerResult, boolean b) {
                            Message msg = new Message();
                            msg.what = RECEIVE_SPEECH_WHAT;
                            Bundle data = new Bundle();
                            data.putString("txtId", txtId);
                            data.putString("function", function);
                            data.putString("speechStr", recognizerResult.getResultString());
                            msg.setData(data);
                            handler.sendMessage(msg);
                        }

                        @Override
                        public void onError(SpeechError speechError) {
                            speechError.getPlainDescription(true);
                        }
                    });
                    //4.开始听写
                    iatDialog.show();
                }
            });

        }

    }


    private MaterialDialog dialog;

    private class ReloadRunnable implements Runnable {

        @Override
        public void run() {
            if (dialog != null) {
                dialog.cancel();
            }
            if (NetUtils.isConnected(MainActivity.this)) {
                loadUrl();
            } else {
                dialog = new MaterialDialog.Builder(MainActivity.this)
                        .title(R.string.dialog_title_net_unconnected)
                        .content(R.string.dialog_content_net_unconnected_2)
                        .cancelable(false)
                        .negativeText(R.string.dialog_btn_exit)
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                //退出程序
                                app.appExit();
                            }
                        })
                        .show();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK) {
            webView.loadUrl("javascript: history.back();");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        unregisterReceiver(netChangeReceiver);
        webView.setWebChromeClient(null);
        webView.setWebViewClient(null);
        webView.getSettings().setJavaScriptEnabled(false);
        webView.clearCache(true);
        super.onDestroy();
    }

    /**
     * 检查是否挂载SD卡
     *
     * @return
     */
    private boolean checkSDcard() {
        boolean flag = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (!flag) {
            showShortToast(R.string.sd_un_mount);
        }
        return flag;
    }

    public class XHSWebChromeClient extends WebChromeClient {

        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
            }
            mUploadMessage = uploadMsg;
            selectFile();
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
            }
            mUploadMessage = uploadMsg;
            selectFile();
        }

        // For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
            }
            mUploadMessage = uploadMsg;
            selectFile();
        }


        //Android 5.0+
        @Override
        @SuppressLint("NewApi")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            if (mUploadCallbackAboveL != null) {
                mUploadCallbackAboveL.onReceiveValue(null);
            }
            mUploadCallbackAboveL = filePathCallback;
            selectFile();
            return true;
        }
    }


    private void selectFile() {
        if (!checkSDcard()) return;

        AlertDialog dialog = new AlertDialog.Builder(this).setItems(R.array.file_select_array, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    //选择文件
                    case 0:
                        choosePic();
                        break;
                    //拍照上传
                    case 1:
                        openCamera();
                        break;
                    default:
                        break;
                }
            }
        }).setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (mUploadCallbackAboveL != null) {
                    Uri[] uris = new Uri[1];
                    uris[0] = Uri.parse("");
                    mUploadCallbackAboveL.onReceiveValue(uris);
                    mUploadCallbackAboveL = null;
                } else {
                    mUploadMessage.onReceiveValue(Uri.parse(""));
                    mUploadMessage = null;
                }
            }
        }).show();
    }

    /**
     * 打开照相机
     */
    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraPath = Environment.getExternalStorageDirectory().getPath() + "/westar/camera/" + (System.currentTimeMillis() + ".jpg");
        // 必须确保文件夹路径存在，否则拍照后无法完成回调
        File vFile = new File(cameraPath);
        if (!vFile.exists()) {
            File vDirPath = vFile.getParentFile();
            vDirPath.mkdirs();
        } else {
            if (vFile.exists()) {
                vFile.delete();
            }
        }
        cameraUri = Uri.fromFile(vFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
        startActivityForResult(intent, CAMERA_REQUEST_CODE);
    }

    /**
     * 本地相册选择图片
     */
    private void choosePic() {
        Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);
        innerIntent.setType("image/*"); // 查看类型
        Intent wrapperIntent = Intent.createChooser(innerIntent, null);
        startActivityForResult(wrapperIntent, CHOOSER_REQUEST_CODE);
    }

    private class MRunnable implements Runnable {
        @Override
        public void run() {

            long time = System.currentTimeMillis() - touchTimes;

            handler.postDelayed(this, PLAY_DELAYMILLIS);
            if (time > DELAYMILLIS) {
//                loadUrl();
                //刷新页面
                webView.reload();
                touchTimes = System.currentTimeMillis();
            }
        }
    }


}
